# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_Chat_session_id'
  
  private
  def authorize
    unless session[:user_id]
      flash[:notice] = "Please login"
      redirect_to :controller => 'welcome'
    else
      @current_user = User.find(session[:user_id])
    end
  end
  
  def clean_up
    rooms = Chatroom.find(:all)
    rooms.each do |r|
      if r.users.blank?
        r.messages.each do |m|
          m.destroy
        end
        r.destroy
      end
    end
  end
  
  def current_room
    if @current_user.chatroom.nil?
      @current_chatroom = nil
    else
      @current_chatroom = @current_user.chatroom
    end
  end
  
  def change_room(room)
    if !room.nil?
      @current_user.chatroom = room
      if @current_user.save
        return true
      end
    end
    return false
  end
  
  def chat_error(msg = nil)
    flash[:notice] = msg || "An error occured!"
    redirect_to :controller => :chat, :action => :index
  end

end
